package xmlGenerator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


@SuppressWarnings("deprecation")
public class RequestXMLGenerator {

	
	private Document dom;
	private String username;
	private String password;
	private List<String> titles;
	private boolean timesCited;
	private boolean related;

	//Constuctor
	public RequestXMLGenerator(List<String> listTitle, Boolean timesCited, Boolean related) {
		
		
		//Get a DOM object
		createDocument();
		
		username = "sgalvaro@gmail.com";
		password = "1234";
		titles = listTitle;
		this.timesCited=timesCited;
		this.related = related;
		
	}

	public void generateXML(){
		System.out.println("Started .. ");
		createDOMTree();
		printToFile();
		System.out.println("Generated file successfully.");
	}
	

	

	/**
	 * Using JAXP in implementation independent manner create a document object
	 * using which we create a xml tree in memory
	 */
	private void createDocument() {

		//get an instance of factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
		//get an instance of builder
		DocumentBuilder db = dbf.newDocumentBuilder();

		//create an instance of DOM
		dom = db.newDocument();

		}catch(ParserConfigurationException pce) {
			//dump it
			System.out.println("Error while trying to instantiate DocumentBuilder " + pce);
			System.exit(1);
		}

	}

	/**
	 * The real workhorse which creates the XML structure
	 */
	private void createDOMTree(){

		//Create the root element 
		Element root = dom.createElement("request");
		root.setAttribute("xmlns", "http://www.isinet.com/xrpc41");
		dom.appendChild(root);
		
		
		// <fn> element
		Element fn = dom.createElement("fn");
		fn.setAttribute("name", "LinksAMR.retrieve");
		root.appendChild(fn);
		
		// (big) <list> element
		Element list = dom.createElement("list");
		fn.appendChild(list);
		
		
		
		
		//Username and password block
		Comment cUser = dom.createComment("WHO'S REQUESTING");
		list.appendChild(cUser);
		Element userMap = dom.createElement("map");
		list.appendChild(userMap);
		Element user = dom.createElement("val");
		user.setAttribute("name", "username");
		user.appendChild(dom.createTextNode(username));
		Element pass = dom.createElement("val");
		pass.setAttribute("name", "password");
		pass.appendChild(dom.createTextNode(password));
		userMap.appendChild(user);
		userMap.appendChild(pass);
		
		//What's block
		Comment what = dom.createComment("WHAT'S REQUESTED");
		list.appendChild(what);
		Element whatMap = dom.createElement("map");
		list.appendChild(whatMap);
		Element whatList = dom.createElement("list");
		whatList.setAttribute("name", "WOS");
		whatMap.appendChild(whatList);
		//Request for timesCited
		if(timesCited){
		Element whatTimesCited = dom.createElement("val");
		whatTimesCited.appendChild(dom.createTextNode("timesCited"));
		whatList.appendChild(whatTimesCited);
		}
		//Request related articles
		if(related){
			Element whatRelated = dom.createElement("val");
			whatRelated.appendChild(dom.createTextNode("citingArticlesURL"));
			whatList.appendChild(whatRelated);
		}
		
		
		Comment endWhat = dom.createComment("end return data");
		list.appendChild(endWhat);
		
		
		Comment lookComment = dom.createComment("LOOKUP DATA");
		list.appendChild(lookComment);
		
		Element query = dom.createElement("map");
		list.appendChild(query);
		
		//Search loop
		for(int j=0;j<titles.size();j++){
			Comment queryComment = dom.createComment("QUERY cite_id"+(j+1));
			query.appendChild(queryComment);
			Element lookMap = dom.createElement("map");
			lookMap.setAttribute("name", "cite_id"+(j+1));
			query.appendChild(lookMap);
			
			//Articles
			Element lookCiteMap = dom.createElement("val");
			lookCiteMap.setAttribute("name", "atitle");
			lookCiteMap.appendChild(dom.createTextNode(titles.get(j)));
			lookMap.appendChild(lookCiteMap);
			
			//List of authors
			Element authorList = dom.createElement("list");
			authorList.setAttribute("name", "authors");
			lookMap.appendChild(authorList);
				//Authors looop
				for(int i=0;i<3;i++){
				Element valAuthor = dom.createElement("val");
				authorList.appendChild(valAuthor);
				valAuthor.appendChild(dom.createTextNode("Author"+i));
				}
		}



	}



	/**
	 * This method uses Xerces specific classes
	 * prints the XML document to file.
     */
	private void printToFile(){

		try
		{
			//print
			OutputFormat format = new OutputFormat(dom);
			format.setIndenting(true);

			//to generate output to console use this serializer
			//XMLSerializer serializer = new XMLSerializer(System.out, format);


			//to generate a file output use fileoutputstream instead of system.out
			XMLSerializer serializer = new XMLSerializer(
			new FileOutputStream(new File("src/main/resources/xml/query.xml")), format);

			serializer.serialize(dom);

		} catch(IOException ie) {
		    ie.printStackTrace();
		}
	}
	
	
}
